cc.Class({
    extends: cc.Component,

    properties: {
        dataEventHandler:null,
        roomId:null,
        maxNumOfGames:0,
        numOfGames:0,
        conf:null,
        seatIndex:-1,
        seats:null,
        turn:-1,
        button:-1,
        gamestate:"",
        showpai:[],
        isOver:false,
        isEnd:false,
        dissoveData:null,
        location:[],
        ipsResult:[],
        // 是否为投降结束
        isDissolveOver:false,
        // 发牌开始坐席
        szone:0,
        sztwo:0,
        // 俱乐部信息
        clubid:null,
        clubname:null,
        // 重连控制
        // isReconnect:false,
        // connectRet:null
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },
    
    reset:function(){
        this.dissoveData=null;
        this.turn = -1;
        // this.button = -1;
        this.szone=0;
        this.sztwo=0;
        this.gamestate = "";
        this.showpai=[];
        for(var i = 0; i < this.seats.length; ++i){
            this.seats[i].holds = [];
            this.seats[i].folds = [];
            this.seats[i].jiaofen = []
        }
    },
    // 游戏场景退出时清除数据
    clear:function(){
        this.dataEventHandler = null;
        if(this.isOver == null){
            this.seats = null;
            this.roomId = null;
            this.maxNumOfGames = 0;
            this.numOfGames = 0;
            this.conf=null;
            this.seatIndex=null;
            this.button=null;
            this.turn=null;
            this.gamestate=null;
            this.showpai=null;
            this.dissoveData=null;
            this.location=null;
            this.ipsResult=null;
            this.szone=null;
            this.sztwo=null;
            this.isDissolveOver=null
        }
    },
    
    dispatchEvent(event,data){
        if(this.dataEventHandler){
            this.dataEventHandler.emit(event,data)
        }    
    },
    
    getSeatIndexByID:function(userId){
        for(var i = 0; i < this.seats.length; ++i){
            var s = this.seats[i];
            if(s.userid == userId){
                return i
            }
        };
        return -1
    },
    getNameByID:function(userId){
        for(var i = 0; i < this.seats.length; ++i){
            var s = this.seats[i];
            if(s.userid == userId){
                return s.name
            }
        };
        return userId
    },
    isOwner:function(){
        return this.seatIndex == 0
    },
    
    getSeatByID:function(userId){
        var seatIndex = this.getSeatIndexByID(userId);
        var seat = this.seats[seatIndex];
        return seat
    },
    
    getSelfData:function(){
        return this.seats[this.seatIndex]
    },
    // 根据IP存储结果（是否同IP）
    initIpsResult:function(){
        this.ipsResult=[];
        for (var i = 0; i < this.seats.length-1; i++) {
            var ip=this.seats[i].ip;
            
            if (!ip) {return};
            if (this.seats[i].userid==0) {
                ip=null
            };
            if (this.seats[i+1]) {
                if(ip==this.seats[i+1].ip&&this.seats[i+1].userid!=0){
                    this.ipsResult.push(true)
                }else{
                    this.ipsResult.push(false)
                }
            };
            if (this.seats[i+2]) {
                if(ip==this.seats[i+2].ip&&this.seats[i+2].userid!=0){
                    this.ipsResult.push(true)
                }else{
                    this.ipsResult.push(false)
                }
            };
            if (this.seats[i+3]) {
                if(ip==this.seats[i+3].ip&&this.seats[i+3].userid!=0){
                    this.ipsResult.push(true)
                }else{
                    this.ipsResult.push(false)
                }
            }
        }
    },
    getLocalIndex:function(index){
        // console.log("getLocalIndex",index);
        var seatsNum=this.seats.length;
        var localIndex=(index - this.seatIndex + seatsNum) % seatsNum;
        console.log("getLocalIndex",index,"localIndex",localIndex);
        return localIndex
    },
    prepareReplay:function(roomInfo,detailOfGame){
        console.log("prepareReplay","roomInfo",roomInfo,"detailOfGame",detailOfGame);
        this.roomId = roomInfo.id;
        this.seats = roomInfo.seats;
        this.turn = detailOfGame.base_info.button;
        var baseInfo = detailOfGame.base_info;
        for(var i = 0; i < this.seats.length; ++i){
            var s = this.seats[i];
            s.seatindex = i;
            s.score = null;
            s.holds = baseInfo.game_seats[i];
            s.folds = [];
            console.log(s);
            if(cc.vv.userMgr.userId == s.userid){
                this.seatIndex = i
            }
        };
        this.conf = {
            type:baseInfo.type
        }
    },
    initHandlers:function(){
        var self = this;
        cc.vv.net.addHandler("login_result",function(data){
            console.log("login_result",data);
            if(data.errcode === 0){
                var data = data.data;
                self.roomId = data.roomid;
                // 保存用于大结算展示的房号
                self.endRoomId=data.roomid;
                self.conf = data.conf;
                self.maxNumOfGames = data.conf.maxGames;
                self.numOfGames = data.numofgames;
                self.seats = data.seats;
                self.seatIndex = self.getSeatIndexByID(cc.vv.userMgr.userId);
                self.isOver = false;
                self.isEnd=false;
                // 先重置数据
                self.reset();
                self.location=data.seats[0].location;
                self.initIpsResult();
                // 俱乐部房间信息保存
                self.clubid=data.clubid;
                self.clubname=data.clubname
            }else{
                console.log(data.errmsg);
                cc.vv.userMgr.login() 
            }
        });
                
        cc.vv.net.addHandler("login_finished",function(data){
            console.log("login_finished");
            // if (self.isReconnect) {
            //     console.log("重连");
            //     self.dispatchEvent("reconnectInit");
            //     self.isReconnect=false
            // }else{
                cc.director.loadScene("mjgame");
                console.log("切换游戏场景结束")
            // }
            // cc.director.loadScene("mjgame");
            // console.log("切换游戏场景结束")
        });

        cc.vv.net.addHandler("exit_result",function(data){
            self.roomId = null;
            self.turn = -1;
            self.seats = null
        });
        
        cc.vv.net.addHandler("exit_notify_push",function(data){
           var userId = data;
           var s = self.getSeatByID(userId);
           if(s != null){
               s.userid = 0;
               s.name = "";
               s.ip="";
               self.initIpsResult();
               self.dispatchEvent("user_state_changed",s)
           }
        });
        
        cc.vv.net.addHandler("dispress_push",function(data){
            self.roomId = null;
            self.turn = -1;
            self.seats = null
        });
                
        cc.vv.net.addHandler("disconnect",function(data){
            console.log("websocket执行重连  function start");
            if(self.roomId == null){
                console.log("websocket执行重连  romm为空");
                cc.director.loadScene("mjhall")
            }else{
                if(self.isEnd == false){
                    cc.vv.userMgr.oldRoomId = self.roomId;
                    var disconnectEvent = function() {
                        //等待reconnce加载成功
                        if (cc.vv.net.isReconnectOk) {
                            self.dispatchEvent("disconnect");
                            cc.vv.net.isReconnectOk = false   //节点监听false
                        } else {
                            setTimeout(disconnectEvent, 2000)
                        }
                    };
                    disconnectEvent();
                    console.log("websocket执行重连  发送节点重连事件")              
                }else{
                    self.roomId = null;
                    console.log("websocket执行重连  游戏已经结束romm为空")
                }
            }
        });
        
        cc.vv.net.addHandler("new_user_comes_push",function(data){
            console.log("new_user_comes_push",data);
            // console.log("新用户加入",data);
            // {"userid":49,"ip":"","score":0,"name":"","online":true,"ready":true,"seatindex":0}
            var seatIndex = data.seatindex;
            if(self.seats[seatIndex].userid > 0){
                self.seats[seatIndex].online = true
            }else{
                data.online = true;
                self.seats[seatIndex] = data
            };
            self.location=data.location;
            self.initIpsResult();
            self.dispatchEvent('new_user',self.seats[seatIndex])
        });
        
        cc.vv.net.addHandler("user_state_push",function(data){
            // 防止坐席已清空时操作报错(解散房间)
            if (!self.seats) {return};
            console.log("user_state_push",data);
            var userId = data.userid;
            var seat = self.getSeatByID(userId);
            seat.online = data.online;
            self.dispatchEvent('user_state_changed',seat)
        });
        
        cc.vv.net.addHandler("user_ready_push",function(data){
            console.log("user_ready_push");
            var userId = data.userid;
            var seat = self.getSeatByID(userId);
            seat.ready = data.ready;
            cc.vv.audioMgr.playSFX("sfx_ready.mp3");
            self.dispatchEvent('user_ready_changed',seat)
        });    
        // 游戏开始，下步定庄
        cc.vv.net.addHandler("game_begin_push",function(data){
            // index  //index游戏开始的坐席
            console.log('game_begin_push',data);
            self.isOver=false;
            self.isDissolveOver=false;
            // 更新庄家防止出现两庄
            self.button=-1;
            self.gamestate = "begin";
           
            for(var i = 0; i < self.seats.length; ++i){
                var s = self.seats[i];
                // 清楚上局扣分数据
                s.koufen=null;
                s.qiangzhuang=-1
            };
            self.dispatchEvent('game_begin',data)
        });
        // 抢庄推送，通知用户抢庄(牌九抢庄模式)
        cc.vv.net.addHandler("game_qiangzhuang_push",function(data){
            console.log('game_qiangzhuang_push',data);
            self.gamestate="qiangzhuang";
            self.dispatchEvent('game_qiangzhuang',data)
        });
        // 抢庄推送，通知用户其他用户抢庄选择(牌九抢庄模式)
        cc.vv.net.addHandler("game_qiangzhuang_notify_push",function(data){
            console.log('game_qiangzhuang_notify_push',data);
            self.seats[data.seatindex].qiangzhuang=data.qiangzhuang;
            self.dispatchEvent('game_qiangzhuang_notify',data)
        });
        // 定庄推送，通知用户定庄(牌九)
        cc.vv.net.addHandler("game_dingzhuang_push",function(data){
            // {zhuang:1}
            self.button=data.zhuang;
            console.log('game_dingzhuang_push',data);
            self.dispatchEvent('game_dingzhuang',data)
        });
        // 叫分推送，通知用户压分(牌九)
        cc.vv.net.addHandler("game_jiaofen_push",function(data){
            console.log('game_jiaofen_push',data);
            self.gamestate="jiaofen";
            // 不立马执行，抢庄动画结束才执行(放在MJRoom控制)
            if (self.conf.bankertype==1&&self.numOfGames%2==0) {
                console.log("抢庄模式，双数局叫分执行");
                self.dispatchEvent('game_jiaofen',data)
            }else if(self.conf.bankertype==0){
                setTimeout(function(){
                    self.dispatchEvent('game_jiaofen',data)
                },1000)
            }
        });
        // 叫分通知推送，通知用户玩家已选压分(牌九)
        cc.vv.net.addHandler("game_jiaofen_notify_push",function(data){
            // {seatindex: 1, fenOne: 35, fenTwo: 50}
            console.log('game_jiaofen_notify_push',data);
            cc.vv.audioMgr.playSFX("bet.mp3");
            // 改写数据
            var seat=self.seats[data.seatindex];
            seat.scoreone=data.fenOne;
            seat.scoretwo=data.fenTwo;
            self.dispatchEvent('game_jiaofen_notify',data)
        });
        // 叫分结束通知推送，通知用户玩家压分阶段结束(牌九)
        cc.vv.net.addHandler("game_jiaofen_end_notify_push",function(data){
            console.log('game_jiaofen_end_notify',data);
            self.dispatchEvent('game_jiaofen_end_notify_push',data)
        });
        // 游戏开始.下步出牌
        cc.vv.net.addHandler("game_playing_push",function(data){
            console.log('game_playing_push',data);
            self.hupaiData=null;
            // {zhuse:1} 
            self.gamestate = "playing"; 
            // 记录色子
            self.szone=data.szone;
            self.sztwo=data.sztwo;
            // console.log("发送事件game_playing");
            self.dispatchEvent('game_playing')
            // console.log("发送事件结束");
        });
        // 手牌推送：
        cc.vv.net.addHandler("game_holds_push",function(data){
            console.log('game_holds_push',data); 
            for(var i = 0; i < self.seats.length; ++i){
                var s = self.seats[i]; 
                // s.ready = false;
                s.chupai=[];
                s.holds=data.holds;
                s.folds=[]
            };
            var seat = self.getSelfData();
            seat.holds = data;
            self.dispatchEvent('game_holds')
        });
        // 配牌推送，通知用户配牌(牌九)
        cc.vv.net.addHandler("game_peipai_push",function(data){
            console.log('game_peipai_push',data);
            self.dispatchEvent('game_peipai',data)
        });
        // 配牌结束通知推送，通知用户玩家配牌阶段结束(牌九)(别人的配牌)
        cc.vv.net.addHandler("game_peipai_notify_push",function(data){
            console.log('game_peipai_notify_push',data);
            var seat=self.seats[data.seatindex];
            seat.folds=[-1,-1,-1,-1];
            self.dispatchEvent('game_peipai_notify',data)
        });
        // 配牌结束通知推送，通知用户玩家配牌阶段结束(牌九)(自己的配牌)
        cc.vv.net.addHandler("game_peipai_result_notify_push",function(data){
            console.log('game_peipai_result_notify_push',data);
            self.dispatchEvent('game_peipai_result_notify',data)
        });
        // 游戏局数推送
        cc.vv.net.addHandler("game_num_push",function(data){
            self.numOfGames = data;
            self.dispatchEvent('game_num',data)
        });
        // 十六张底牌推送
        cc.vv.net.addHandler("game_showpai_push",function(data){
            console.log('game_showpai_push',data);
            self.showpai=data.pai;
            self.dispatchEvent('game_showpai',data)
        });
        // 标识解散的结束
        cc.vv.net.addHandler("game_dissolve_push",function(data){
            console.log('game_dissolve_push',data);
            self.isDissolveOver=true;
            self.dispatchEvent('game_dissolve',data)
        });
        // 结束(大小结算的结束均为)
        cc.vv.net.addHandler("game_over_push",function(data){
            console.log("game_over_push",data);
            if (self.conf.type==10) {
                console.log("牌九结束");
                self.isOver=true;
                // 更新数据
                for(var i = 0; i < self.seats.length; ++i){
                    var seat = self.seats[i];
                    if (data.results.length>0) {
                        var sd = data.results[i];
                        if (sd.totalscore||sd.totalscore==0) {
                            seat.score=sd.totalscore
                        };
                        // 扣分
                        seat.koufen=sd.score
                    };
                    seat.ready=false;
                    // 清空叫分
                    seat.scoreone=-1;
                    seat.scoretwo=-1
                };
                if (data.endinfo==null) {
                    self.dispatchEvent('game_over',data.results)
                }else{
                    self.isEnd=true;
                    self.endinfo=data.endinfo;
                    if (data.results.length>0) {
                        // 解散的结束直接大结算
                        if (self.isDissolveOver) {
                            self.dispatchEvent('game_end',data.endinfo)
                        }else{
                            self.dispatchEvent('game_over',data.results);
                            // 大结算（已经做到mjgame准备按钮触发）
                            // setTimeout(function(){
                            //     self.dispatchEvent('game_end',data.endinfo)
                            // },8000)
                        }
                    }else{
                        self.dispatchEvent('game_end',data.endinfo)
                    }
                }
            };
            self.reset()
        });
        // 重连数据更新
        cc.vv.net.addHandler("game_sync_push",function(data){
            console.log("game_sync_push",data);
            self.gamestate = data.state;
            // 十六张底牌
            self.showpai=data.showpai;
            self.turn = data.turn;
            // 抢庄状态不定庄
            if (self.gamestate!="qiangzhuang") {
                self.button = data.button
            };
            for(var i = 0; i < self.seats.length; ++i){
                var seat = self.seats[i];
                var sd = data.seats[i];
                seat.chupai=[];
                if (sd) {
                    seat.holds = sd.holds;
                    seat.folds = sd.folds;
                    if (sd.peipaione&&sd.peipaitwo) {
                        if (sd.peipaione.length>0&&sd.peipaitwo.length>0) {
                            seat.chupai=sd.peipaione.concat(sd.peipaitwo)
                        }
                    };
                    seat.qiangzhuang=sd.qiangzhuang;
                    seat.scoreone = sd.scoreone;
                    seat.scoretwo = sd.scoretwo;
                    // 是否已经配牌
                    if (sd.haspeipai) {
                        seat.folds=[-1,-1,-1,-1]
                    }
                }
            }
        });
        cc.vv.net.addHandler("chat_push",function(data){
            self.dispatchEvent("chat_push",data)  
        });
        
        cc.vv.net.addHandler("quick_chat_push",function(data){
            self.dispatchEvent("quick_chat_push",data)
        });
        
        cc.vv.net.addHandler("emoji_push",function(data){
            self.dispatchEvent("emoji_push",data)
        });
        
        cc.vv.net.addHandler("dissolve_notice_push",function(data){
            console.log("dissolve_notice_push"); 
            console.log(data);
            self.dissoveData = data;
            self.dispatchEvent("dissolve_notice",data)
        });
        
        cc.vv.net.addHandler("dissolve_cancel_push",function(data){
            console.log("dissolve_cancel_push",data);
            self.dissoveData = null;
            self.dispatchEvent("dissolve_cancel",data)
        });
        
        cc.vv.net.addHandler("voice_msg_push",function(data){
            self.dispatchEvent("voice_msg",data)
        });
    },

    getWanfa:function(conf){
        if (!conf) {
            conf=this.conf
        };
        var ret=[];
        if (conf.type==10) {
            // ret.push("牌九");
            ret.push(conf.maxGames+"局");
            if (conf.bankertype==0) {
                ret.push("轮庄")
            }else if (conf.bankertype==1) {
                ret.push("抢庄")
            }
        };
        return ret.join(" ")
    },
    getNowFormatDate:function(){
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month
        };
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate
        };
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate
    },
    connectGameServer:function(data){
        console.log("connectGameServer",data);
        this.dissoveData = null;
        cc.vv.net.ip = data.ip + ":" + data.port;
        console.log(cc.vv.net.ip);
        var self = this;

        var onConnectOK = function(){
            console.log("onConnectOK");
            var sd = {
                token:data.token,
                roomid:data.roomid,
                time:data.time,
                sign:data.sign
            };
            cc.vv.net.send("login",sd)
        };
        
        var onConnectFailed = function(){
            console.log("failed.");
            if (!self.isReconnectOk) {
                cc.vv.wc.hide()
            }
        };
        // 重连没有显示
        // if (!this.isReconnect) {
            cc.vv.wc.show("正在进入房间")
        // };
        
        cc.vv.net.connect(onConnectOK,onConnectFailed)
    }

    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});
